package com.SouthernWall_404.AgeRight.Common.API.MissionAPI;

import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.ListTag;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.Items;

import java.util.ArrayList;
import java.util.List;

public class RewardInfo {

    public List<ItemStack> rewards = new ArrayList<>();

    public RewardInfo(List<ItemStack> rewards) {
        this.rewards = rewards;
    }

    public RewardInfo(ItemStack reward) {
        rewards.add(reward);
    }

    // 无参构造函数用于NBT加载
    public RewardInfo() {
    }

    /**
     * 将奖励信息保存到NBT标签中
     */
    public CompoundTag saveToNBT() {
        CompoundTag tag = new CompoundTag();
        ListTag rewardsList = new ListTag();

        for (ItemStack stack : rewards) {
            CompoundTag itemTag = new CompoundTag();
            stack.save(itemTag);
            rewardsList.add(itemTag);
        }

        tag.put("rewards", rewardsList);
        return tag;
    }

    /**
     * 从NBT标签中加载奖励信息
     */
    public static RewardInfo loadFromNBT(CompoundTag tag) {
        RewardInfo rewardInfo = new RewardInfo();

        if (tag.contains("rewards")) {
            ListTag rewardsList = tag.getList("rewards", 10); // 10 = CompoundTag

            for (int i = 0; i < rewardsList.size(); i++) {
                CompoundTag itemTag = rewardsList.getCompound(i);
                ItemStack stack = ItemStack.of(itemTag);

                // 确保物品不为空
                if (stack.getItem() != Items.AIR) {
                    rewardInfo.rewards.add(stack);
                }
            }
        }

        return rewardInfo;
    }

    /**
     * 给玩家发放奖励
     */
    public void giveReward(Player player) {
        for (ItemStack reward : rewards) {
            if (!reward.isEmpty()) {
                // 尝试添加到玩家物品栏，如果满了就掉落在地上
                if (!player.addItem(reward.copy())) {
                    player.spawnAtLocation(reward.copy());
                }
            }
        }
    }
}